package ft.app.gtig.portal.controllers.api;

import javax.inject.Inject;
import java.util.List;

import com.haulmont.chile.core.model.MetaClass;
import com.haulmont.cuba.core.app.DataService;
import com.haulmont.cuba.core.global.LoadContext;
import com.haulmont.cuba.core.global.Metadata;
import com.haulmont.cuba.core.global.View;
import com.haulmont.cuba.restapi.ConversionFactory;
import com.haulmont.cuba.restapi.Converter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;


import ft.app.gtig.entity.TimelineEvent;

@RestController
@RequestMapping("/app/events")
public class EventsController {

    protected Logger log = LoggerFactory.getLogger(getClass());

    @Inject
    protected ConversionFactory conversionFactory;

    @Inject
    protected DataService dataService;

    @Inject
    protected Metadata metadata;

    @CrossOrigin(origins = "*")
    @RequestMapping(value = "/upcoming", method = RequestMethod.GET)
    public List<TimelineEvent> upcoming() throws Exception {

        LoadContext<TimelineEvent> loadContext = LoadContext.create(TimelineEvent.class)
                .setQuery(LoadContext.createQuery("select e from gtig$TimelineEvent e order by e.timeBegin asc"))
                .setView("timelineEvent-list");

        List<TimelineEvent> entities = dataService.loadList(loadContext);

        for(TimelineEvent entity : entities) {
            log.info(entity.getTitle());
        }

        log.info(entities.toString());

        MetaClass metaClass = metadata.getClassNN(TimelineEvent.class);

        Converter converter = conversionFactory.getConverter("json");


        log.info(converter.process((List) entities, metaClass, loadContext.getView()));


        return entities;

    }
}